//
//  HomeRootViewController.m
//  YunDongAdmin
//
//  Created by lqq on 2018/9/4.
//  Copyright © 2018年 cloudfighting.com. All rights reserved.
//

#import "HomeRootViewController.h"
#import "I_Statistics.h"
#import "I_Gym.h"
#import "GymOverviewView.h"
#import "YDWebView.h"
#import "AddCoachViewController.h"

//test
#import "UIButton+Extension.h"
#import "GymListViewController.h"

@interface HomeRootViewController ()<WKNavigationDelegate,YDWebViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) M_GymOverview *gymOverview;
@property (nonatomic, strong) M_StatMember *statMember;
@property (nonatomic, strong) YDWebView *webView;
@end

@implementation HomeRootViewController
{
    BOOL _webLoadFinished;
}

#pragma mark Class Method
+ (instancetype)controller
{
    HomeRootViewController *vc = [[HomeRootViewController alloc] init];
    return vc;
}

#pragma mark Life Circle
- (void)viewDidLoad
{
    [super viewDidLoad];
    //进来请求门店列表，看是否需要更新门店
    [self requestGymList];
    [self configUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(editGymSuccess) name:kNotificationEditGymSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground) name:@"ApplicationWillEnterForeground" object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationItem.title = RI.account.brandName;

    [self requestAllGymOverview];
    [self requestStatMember];
    if (!_webLoadFinished) {
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:Url_For_Home]]];

    }
}

- (void)dealloc
{
    NSLog(@"%s",__func__);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark Config/UI
- (void)configUI
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.insetTop = 10;
    _tableView.backgroundColor = TP.controllerBackColor;
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    
    _webView = [[YDWebView alloc] init];
    _webView.frame = CGRectMake(0, 0, kDeviceWidth, 10);
    _tableView.tableFooterView = _webView;
    _webView.YDWebDelegate = self;
    [_webView.bridge setWebViewDelegate:self];
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:Url_For_Home]]];

}


- (void)refreshHeaderView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, 0)];
    CGFloat headerViewHeight = 0;
    GymOverviewView *overviewView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([GymOverviewView class]) owner:nil options:nil].lastObject;
    [headerView addSubview:overviewView];
    [overviewView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(headerView);
        make.height.equalTo(@(140));
    }];
    [overviewView refreshUIWithGymOverview:_gymOverview isCheckAll:YES];
    headerViewHeight += 140;
    
    headerViewHeight += 10;
    
    
    CGFloat statMemberViewHeight = 0;
    UIView *statMemberView = [[UIView alloc] init];
    [headerView addSubview:statMemberView];
    statMemberView.backgroundColor = [UIColor whiteColor];
    UIView *statMemberTopView = [statMemberView addViewKeepTopWithHeight:50 topSpace:0 leftSpace:0 rightSpace:0 backColor:[UIColor whiteColor]];
    [statMemberTopView addVCenterImageViewKeepLeft:20 width:20 height:20 imageName:@"ic_40_huiyuanshuliang"];
    [statMemberTopView addVCenterLabelKeepLeft:48 text:@"会员数量" textColor:HEXColor(@"#333333 ") font:RegularFont(14)];
    
    statMemberViewHeight += 50;
    if (_statMember.total > 0 && _statMember.statList.count > 0) {
        [statMemberTopView addVCenterLabelKeepRight:20 text:[NSString stringWithFormat:@"累计会员：%ld",(long)_statMember.total] textColor:HEXColor(@"#4A4A4A") font:RegularFont(14)];
        
        CGFloat gymListBackViewHeight = _statMember.statList.count * 20;
        statMemberViewHeight += (gymListBackViewHeight + 10*2);
        UIView *gymListBackView = [[UIView alloc] init];
        [statMemberView addSubview:gymListBackView];
        [gymListBackView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(statMemberView);
            make.top.equalTo(statMemberTopView.mas_bottom).offset(10);
            make.height.equalTo(@(gymListBackViewHeight));
        }];
        
        for (int i = 0 ; i < _statMember.statList.count; i++) {
            M_StatCountDTO *DTO = _statMember.statList[i];
            UIView *gymBackView = [[UIView alloc] init];
            [gymListBackView addSubview:gymBackView];
            [gymBackView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.equalTo(gymListBackView);
                make.top.equalTo(@(i*20));
                make.height.equalTo(@(20));
            }];
            
            //gymNameLabel
            UILabel *gymNameLabel = [[UILabel alloc] init];
            gymNameLabel.textColor = HEXColor(@"#4A4A4A");
            gymNameLabel.text = DTO.gymName;
            gymNameLabel.font = RegularFont(11);
            [gymBackView addSubview:gymNameLabel];
            gymNameLabel.textAlignment = NSTextAlignmentRight;
            [gymNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(gymBackView);
                make.left.equalTo(gymBackView).offset(20);
                make.width.equalTo(@(66));
            }];
            
            //memberCountPercentLabel
            UILabel *memberCountPercentLabel = [[UILabel alloc] init];
            memberCountPercentLabel.textColor = HEXColor(@"#4A4A4A");
            memberCountPercentLabel.text = [NSString stringWithFormat:@"%.1f%%",DTO.ratio*100];
            memberCountPercentLabel.font = RegularFont(11);
            [gymBackView addSubview:memberCountPercentLabel];
//            memberCountPercentLabel.textAlignment = NSTextAlignmentRight;
            [memberCountPercentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(gymBackView);
                make.right.equalTo(gymBackView).offset(0);
                make.width.equalTo(@(52));
            }];
            
            //memberCountLabel
            UILabel *memberCountLabel = [[UILabel alloc] init];
            memberCountLabel.textColor = HEXColor(@"#4A4A4A");
            memberCountLabel.text = [NSString stringWithFormat:@"%ld",(long)DTO.count];
            memberCountLabel.font = RegularFont(11);
            [gymBackView addSubview:memberCountLabel];
//            memberCountLabel.textAlignment = NSTextAlignmentRight;
            [memberCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(gymBackView);
                make.right.equalTo(memberCountPercentLabel.mas_left);
                make.width.equalTo(@(28));
            }];
            
            UIProgressView *progressView = [[UIProgressView alloc] init];
            progressView.progressTintColor = HEXColor(@"#3AA7FF");
            progressView.trackTintColor = HEXColor(@"#E9E9EB");
            progressView.progress = DTO.ratio;
            [gymBackView addSubview:progressView];
            [progressView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(gymNameLabel.mas_right).offset(10);
                make.right.equalTo(memberCountLabel.mas_left).offset(-10);
                make.centerY.equalTo(gymBackView);
                make.height.equalTo(@(3));
            }];
            
        }
    } else {
        CGFloat statMemberEmptyViewHeight = 90;
        statMemberViewHeight += statMemberEmptyViewHeight;
        UIImageView *emptyIcon = [[UIImageView alloc] init];
        emptyIcon.image = IMG_NAME(@"pic_80_home_wujilu");
        [statMemberView addSubview:emptyIcon];
        [emptyIcon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(statMemberView);
            make.width.height.equalTo(@(40));
        }];
//        UILabel *noDataLabel = [[UILabel alloc] init];
//        noDataLabel.text = @"暂无数据";
//        noDataLabel.textColor = HEXColor(@"#9B9B9B");
//        noDataLabel.font = RegularFont(14);
//        [statMemberView addSubview:noDataLabel];
//        [noDataLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.centerX.equalTo(emptyIcon);
//            make.top.equalTo(emptyIcon.mas_bottom).offset(13);
//        }];
        UIButton *addCoachBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [addCoachBtn setTitle:@"暂无数据,添加教练账号" forState:UIControlStateNormal];
        [addCoachBtn setTintColor:HEXColor(@"3AA7FF")];
        addCoachBtn.titleLabel.font  = RegularFont(14);
        [addCoachBtn addTarget:self action:@selector(addCoach) forControlEvents:UIControlEventTouchUpInside];
        [statMemberView addSubview:addCoachBtn];
        [addCoachBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(emptyIcon);
            make.top.equalTo(emptyIcon.mas_bottom).offset(8);
        }];
    }
    
    [statMemberView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(headerView);
        make.height.equalTo(@(statMemberViewHeight));
    }];
    headerViewHeight += statMemberViewHeight;
    headerView.height = headerViewHeight;
    self.tableView.tableHeaderView = headerView;
    
}

#pragma mark Action
- (void)addCoach
{
    AddCoachViewController *addCoachVC = [AddCoachViewController controller];
    [self.navigationController pushViewController:addCoachVC animated:YES];
}


#pragma mark NET

/**
 请求门店列表
 */
- (void)requestGymList
{
    [I_Gym requestGymListOnSuccess:^(NSMutableArray *gymList) {
        BOOL find = NO;
        for (M_Gym *gym in gymList) {
            if ([gym.gymId isEqualToString:RI.currentGym.gymId]) {
                find = YES;
                RI.currentGym = gym;
                break;
            }
        }
        if (!find) {
            RI.currentGym = gymList.firstObject;
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)requestAllGymOverview
{
    WeakSelf(self);
    [I_Statistics requestGymOverviewIsCheckAll:YES onSuccess:^(M_GymOverview *gymOverview) {
        weakself.gymOverview = gymOverview;
        [weakself refreshHeaderView];
    } failure:^(NSError *error) {
        [weakself refreshHeaderView];
    }];
}

- (void)requestStatMember
{
    WeakSelf(self);
    [I_Statistics requestStatMemberIsCheckAll:YES onSuccess:^(M_StatMember *statMember) {
        weakself.statMember = statMember;
        [weakself refreshHeaderView];
    } failure:^(NSError *error) {
        [weakself refreshHeaderView];
    }];
}


#pragma mark Noti
- (void)editGymSuccess
{
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:Url_For_Home]]];

}

- (void)applicationWillEnterForeground
{
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:Url_For_Home]]];
}

#pragma mark YDWebViewDelegate
- (void)webView:(YDWebView *)webView contentSizeDidChanged:(CGSize)size
{
    NSLog(@"%@",NSStringFromCGSize(size));
    _webView.height = size.height;
    _tableView.tableFooterView = _webView;
}
//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"开始加载网页");
    //开始加载网页时展示出progressView
}

//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
    _webLoadFinished = YES;
}

//加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"加载失败");
}

@end
